/**
 * 功能:
 * 作者:周逸健
 * 日期: 2023/10/25 19:41
 */
package com.cgnfz.crm.controller;

import com.cgnfz.crm.entity.RestBean;
import com.cgnfz.crm.entity.vo.request.RegisterVO;
import com.cgnfz.crm.service.EmployeeService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.function.Supplier;

/**
 * 用于验证相关Controller包含用户的注册、重置密码等操作
 */
@Validated
@RestController
@RequestMapping("/api/auth")
@Slf4j
public class AuthorizeController {

    @Resource
    EmployeeService employeeService;


    @PostMapping("/register")
    public RestBean<Void> register(@RequestBody @Valid RegisterVO vo) {
        return this.messageHandle(() -> employeeService.registerAccount(vo));
    }

    @PostMapping("/reset-confirm")
    public RestBean<Void> resetConfirm(@RequestBody @Valid RegisterVO vo) {
        return this.messageHandle(() -> employeeService.resetConfirm(vo));
    }

    @PostMapping("/reset-password")
    public RestBean<Void> resetPassword(@RequestBody @Valid RegisterVO vo) {
        return this.messageHandle(() -> employeeService.resetPassword(vo));
    }


    /**
     * 针对于返回值为String作为错误信息的方法进行统一处理
     *
     * @param action 具体操作
     * @param <T>    响应结果类型
     * @return 响应结果
     */
    private <T> RestBean<T> messageHandle(Supplier<String> action) {
        String message = action.get();
        if (message == null)
            return RestBean.success();
        else
            return RestBean.failure(400, message);
    }

}
